#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from chrikoch.fileManager import ImagesFromBlob
from chrikoch.fileManager import UploadedFiles
import webapp2
import jinja2
import os
import datetime
import urllib
from chrikoch import logger
from chrikoch import fileManager

from google.appengine.ext import db
from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers
#from google.appengine.api import urlfetch
from google.appengine.api import users
from google.appengine.api import images


jinja_environment = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))

class MainHandler(webapp2.RequestHandler):
    def get(self):
        #self.response.out.write('Hello world2!')

        act_date = datetime.datetime.now()
        upload_url = blobstore.create_upload_url('/upload')


        prev_visits = db.GqlQuery('SELECT * '
                                + 'FROM LogEntry '
                                + 'ORDER BY date DESC')

        prev_uploads = db.GqlQuery('SELECT * '
                                + 'FROM UploadedFiles '
                                + 'ORDER BY filename DESC')

        filelist = []
        for file in prev_uploads.run():
            thisfile = ImagesFromBlob(file.filename, file.storagekey)

            filelist.append(thisfile)
            #self.response.out.write(file.filename)
            #self.response.out.write(file.storagekey)
            #self.response.out.write(images.get_serving_url(file.storagekey))

        self.response.out.write(images.IMG_SERVING_SIZES_LIMIT)

        template_values = {
            'user_name': 'Christian',
            'date': act_date,
            'prev_visits': prev_visits,
            'prev_uploads': filelist,
            'upload_url': upload_url
        }

        l = logger.LogEntry(date=act_date,
                            user_agent=self.request.headers['User-Agent'],
                            remote_addr=self.request.remote_addr)
        l.user_agent = self.request.headers['User-Agent']
        l.remote_addr = self.request.remote_addr
        l.put()

        template = jinja_environment.get_template('index.html')
        self.response.out.write(template.render(template_values))

        #res = urlfetch.fetch('https://doodle.com/api1/polls/2utd2wy2r9cziac2')

        #self.response.out.write(res.content)
        self.checkUser();

    def checkUser(self):
        user = users.get_current_user()
        if user:
            greeting = ("Welcome, %s! (<a href=\"%s\">sign out</a>)" %
                        (user.nickname(), users.create_logout_url("/")))
        else:
            greeting = ("<a href=\"%s\">Sign in or register</a>." %
                        users.create_login_url("/"))

        self.response.out.write("<html><body>%s</body></html>" % greeting)

class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
    def post(self):
        upload_files = self.get_uploads('myfile')
        blob_info = upload_files[0]

        self.response.out.write("vor put")

        file2store = UploadedFiles()
        file2store.storeFile(blob_info)
        self.response.out.write("vor put")
        file2store.put()

        self.redirect('/serve/%s' % blob_info.key())

class ServeHandler(blobstore_handlers.BlobstoreDownloadHandler):
    def get(self, resource):
        resource = str(urllib.unquote(resource))
        blob_info = blobstore.BlobInfo.get(resource)
        #self.response.out.write(resource)
        self.send_blob(blob_info)



app = webapp2.WSGIApplication([('/', MainHandler),
                               ('/upload', UploadHandler),
                               ('/serve/([^/]+)?', ServeHandler)],
                              debug=True)
